package twoD.Csg;

import inf.v3d.obj.*;

public class QuadTreeNode {
	private QuadTreeNode[] nodes;
	private double size;
	private double x;
	private double y;
	private boolean isHomogeneous_;

	public QuadTreeNode(CsgNode N, double x, double y, double size) {
		this.x = x;
		this.y = y;
		this.size = size;
		nodes = null;
	}

	private boolean isLeaf() {
		return nodes == null;
	}

	public boolean isHomogeneous() {
		return isHomogeneous_;
	}

	public void draw(CsgNode N, PolygonSet ps) {
		if (this.isLeaf()) {
			if (!isHomogeneous_) {
				ps.insertVertex(this.x, this.y, 0.0, 0);
				ps.insertVertex(this.x + this.size, this.y, 0.0, 0);
				ps.insertVertex(this.x + this.size, this.y + this.size, 0.0, 0);
				ps.insertVertex(this.x, this.y + this.size, 0.0, 0);
				ps.polygonComplete();
			}
		} else {
			for (int i = 0; i < nodes.length; i++)
				nodes[i].draw(N, ps);
		}
	}

	public void refine(CsgNode N, int depth) {
		if (!N.isUniform(this.x, this.y, this.size)) {
			nodes = new QuadTreeNode[4];
			for (int i = 0; i < 2; i++) {
				for (int j = 0; j < 2; j++) {
					nodes[i * 2 + j] = new QuadTreeNode(N, this.x + i
							* this.size / 2, this.y + j * this.size / 2,
							this.size / 2);
					if (depth > 0)
						nodes[i * 2 + j].refine(N, depth - 1);
					else {
						if (!N.isUniform(this.x + i * this.size / 2, this.y + j
								* this.size / 2, this.size / 2))
							nodes[i * 2 + j].isHomogeneous_ = false;
						else
							nodes[i * 2 + j].isHomogeneous_ = true;
					}
				}
			}
			isHomogeneous_ = false;
		} else
			isHomogeneous_ = true;
	}
}
